<script setup  lang="tsx">
import type { SelectTokenProps } from '../Comps/SelectToken.vue';
import type { UseReadyAllReturn } from '../ts/useReadyAll';
import type { SelectWithdrawMethodProps } from './SelectWithdrawMethod.vue';
import type { CurrencyBalance, TiKuanFangShiXiangQing } from '~/api/services/main.api';
import { Skeleton } from '~/components/skeleton';
import { lockRecordPopup } from '../Comps/LockRecord/index.vue';
import SelectToken from '../Comps/SelectToken.vue';
import { toBnInt, toBnVal, toDecimalPlaces } from '../ts/utils';
import Crypto from './Crypto.vue';
import Fiat from './Fiat.vue';
import SelectWithdrawMethod from './SelectWithdrawMethod.vue';

const props = defineProps<{ withdrawReadyQry?: UseReadyAllReturn['withdrawReadyQry'] }>();

const appStore = useAppStore();

lockRecordPopup?.close();

const getIsLoadingRef = computed(() => toValue(props.withdrawReadyQry?.isLoading));

const getCurrencyListRef = computed(() => {
  const list = toValue(props.withdrawReadyQry?.data)?.currency_balance_list || [];
  return list.map(x => ({ ...x, disabled: x.allow_withdraw === 0 }));
});

const currencyName = ref<string>();
const chainName = ref<string>();
const isFiatRef = ref(false);
const currencyInfoRef = ref<CurrencyBalance>();

const methodListRef = ref<SelectWithdrawMethodProps['list']>([]);

const getMethodListLenRef = computed(() => {
  let val = 0;
  for (const x of methodListRef.value) {
    val += x.list.length;
  }
  return val;
});

const selectCurrency: SelectTokenProps['onSelectCurrency'] = (data) => {
  currencyInfoRef.value = data.currencyInfo;
  // activeMethod.value = isFiatRef.value ? methodListRef.value?.[0]?.list?.find(x => !x.is_maintain) || methodListRef.value?.[1]?.list?.find(x => !x.is_maintain) : void 0;
};

const getLabelsRef = computed((): SelectTokenProps['labels'] => [$t('zaeCi53Gn5GnpEcGcybbs'), isFiatRef.value ? $t('29jJbDfgTiKobe9IhjBfM') : $t('iPebTeKtsDGc45qeA0zMl')]);

const isLoadingMethod = ref(false);

const activeMethod = ref<TiKuanFangShiXiangQing>();

const openMethod = ref(false);

function onOpenMethod() {
  if (!isFiatRef.value) {
    openMethod.value = false;
    return;
  }
  if (openMethod.value && !activeMethod.value) {
    return;
  }
  openMethod.value = !openMethod.value;
}

useQuery({
  enabled: () => !!(isFiatRef.value && currencyName.value),
  queryKey: [apis.apiFundWithdrawPaymentMethod.id, currencyName, isFiatRef],
  queryFn: async () => {
    try {
      isLoadingMethod.value = true;
      methodListRef.value = [];
      const data = await apis.apiFundWithdrawPaymentMethod({ currency: currencyName.value });
      methodListRef.value = data ? [{ name: $t('akz4kGGp2Pytm_6nuVp'), list: data.wallet || [] }, { name: $t('fWCtbdEKmRVjixNjjnX0'), list: data.bank || [] }] : [];
      activeMethod.value = void 0;
      // activeMethod.value = methodListRef.value[0]?.list?.find(x => !x.is_maintain) || methodListRef.value[1]?.list?.find(x => !x.is_maintain);
      isLoadingMethod.value = false;
      if (getMethodListLenRef.value > 0 && !openMethod.value && !activeMethod.value) {
        openMethod.value = true;
      }
      return data;
    }
    catch {
      isLoadingMethod.value = false;
      return null;
    }
  },
});

function RenderChain() {
  if (isLoadingMethod.value) {
    return (
      <Skeleton>
        <Skeleton type="rect" width="auto" />
      </Skeleton>
    );
  }
  const methodData = activeMethod.value;
  const isOpen = (openMethod.value || !methodData) && isFiatRef.value;
  const methodImgUrl = methodData?.image_icon ? appStore.joinCdnPath(methodData?.image_icon) : '';
  const methodText = methodData?.name || '';
  return (
    <div
      class={`w-full grid grid-cols-[1fr_auto] cursor-pointer items-center gap-2 bg-sys-layer-a px-3 ${isOpen ? 'rounded-tl-lg rounded-tr-lg' : 'rounded-lg'}`}
      onClick={onOpenMethod}
    >
      {methodData
        ? (methodImgUrl
            ? <img class="h-4.5 max-w-16.5 object-cover" src={methodImgUrl} />
            : <div class="cursor-pointer truncate">{ methodText }</div>
          )
        : <div class="truncate text-[#545863]">{$t('uJzMKsPoTfPUqZtr0Vr')}</div>}
      {isOpen ? <div class="i-mingcute:up-line h-4.5 w-4.5 cursor-pointer" /> : <div class="i-mingcute:down-line h-4.5 w-4.5 cursor-pointer" />}
    </div>
  );
}

function RenderSelectToken() {
  return (
    <SelectToken
      v-model:currency={currencyName.value}
      v-model:chain={chainName.value}
      v-model:isFiat={isFiatRef.value}
      list={getCurrencyListRef.value}
      labels={getLabelsRef.value}
      onSelectCurrency={selectCurrency}
      showBalance={true}
      disabledKey="allow_withdraw"
    >
      {{ chain: isFiatRef.value ? () => RenderChain() : void 0 }}
    </SelectToken>
  );
}

function LoadingComponent() {
  return (
    <Skeleton class="grid grid-cols-2 gap-x-3">
      <Skeleton class="mb-2" type="text" length={8} />
      <Skeleton class="mb-2" type="text" length={8} />
      <Skeleton class="mb-3" type="rect" width="auto" />
      <Skeleton class="mb-3" type="rect" width="auto" />
      <Skeleton class="col-span-full mb-2" type="text" length={8} />
      <Skeleton class="col-span-full mb-3" type="rect" width="auto" />
      <Skeleton class="mb-2" type="text" length={8} />
      <Skeleton class="mb-2 text-right" type="text" length={8} />
      <Skeleton class="col-span-full mb-3" type="rect" width="auto" />
      <Skeleton class="col-span-full mt-6" type="rect" width="auto" />
    </Skeleton>
  );
}

function RenderDefDom() {
  if ((openMethod.value || !activeMethod.value) && isFiatRef.value) {
    if (isLoadingMethod.value) {
      return <RenderSelectToken />;
    }
    return (
      <SelectWithdrawMethod
        v-model:open={openMethod.value}
        v-model:activeMethod={activeMethod.value}
        list={methodListRef.value}
      >
        <RenderSelectToken />
      </SelectWithdrawMethod>
    );
  }

  const getBnv = (v: ReturnType<typeof bignumber>) => v.decimalPlaces() ? toDecimalPlaces(v, false, v.decimalPlaces() || 0) : v;
  const bnBalance = getBnv(toBnVal(currencyInfoRef.value?.balance) || bignumber(0));
  const bnLockedBalance = getBnv(toBnVal(currencyInfoRef.value?.locked_balance) || bignumber(0));
  const bnAvailableBalance = getBnv(toBnVal(bnBalance.minus(bnLockedBalance)) || bignumber(0));

  const commonProps = { currencyInfo: currencyInfoRef.value, bnBalance, bnLockedBalance, bnAvailableBalance };
  const commonSlots = {
    default: RenderSelectToken,
    lockedBalance: () => (
      <div class="mt-1.5 flex items-center justify-end text-xs text-green-500">
        <div class="cursor-pointer underline" onClick={() => lockRecordPopup?.open()}>
          { `${$t('dlTjpDh4y7obyDRd2trYk')}：${isFiatRef.value ? toBnInt(bnLockedBalance).toFormat() : bnLockedBalance.toFormat()}` }
        </div>
      </div>
    ),
  };
  if (isFiatRef.value) {
    return <Fiat {...commonProps} method={activeMethod.value} isLoadingMethod={isLoadingMethod.value}>{commonSlots}</Fiat>;
  }
  return <Crypto {...commonProps} chain={chainName.value}>{commonSlots}</Crypto>;
}
</script>

<template>
  <LoadingComponent v-if="getIsLoadingRef" />
  <div v-else class="flex flex-col text-sm text-sys-text-body lt-mobile:(h-full overflow-y-auto)">
    <RenderDefDom />
    <lockRecordPopup.PresetComponent />
  </div>
</template>
